package com.zhouheng.springbootmultithreading.tuling.threadactiveness;

import lombok.extern.slf4j.Slf4j;

/**
 * @author Fox
 * 死锁
 * 面试技巧：面试官提问什么是死锁，回答通过就录取你
 * 你说，你录取我，我就告诉你什么是死锁；
 * 两个线程互相等待对方持有乙方想要的锁资源却因双方线程锁释放不了时
 */
@Slf4j
public class DeadLockTest {

    private static String a = "a";
    private static String b = "b";

    public static void main(String[] args) {
        Thread threadA = new Thread(() -> {
            synchronized (a) {
                log.debug("threadA进入a同步块，执行中...");
                try {
                    // 打破循环条件，这里可以释放出去，等线程B执行完了来，能解决死锁
//                    a.wait(5000);
                    Thread.sleep(2000);
                    synchronized (b) {
                        log.debug("threadA进入b同步块，执行中...");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "threadA");

        Thread threadB = new Thread(() -> {
            synchronized (b) {
                log.debug("threadB进入b同步块，执行中...");
                synchronized (a) {
                    log.debug("threadB进入a同步块，执行中...");
                }
            }
        }, "threadB");

        threadA.start();
        threadB.start();

    }

}
